import json
import math
import random
from django.db.models import Q
from userauth.models import LoginRecord, UserInfo, UserGroup
import pymongo
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, Http404
from django.shortcuts import render
# import matplotlib.pyplot as plt                #加载matplotlib用于数据的可视化
from sklearn.decomposition import PCA  # 加载PCA算法包
from numpy import *
#import pandas as pd
import datetime
from django.contrib.auth.decorators import permission_required
import xlrd
'''
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["test3"]
mycol1 = mydb["fabing"]
mycol2 = mydb["siwang"]
'''
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["test3"]

mycol1 = mydb["questionnaire1"]  # 存储脑出血患者调查问卷
mycol2 = mydb["questionnaire2"]  # 存储健康人群调查问卷
mycol4 = mydb["questionnaire4"]  # 存储健康人群调查问卷(体检中心)
mycol5 = mydb["questionnaire5"]  # 存储脑出血患者调查问卷(医院)
mycol6 = mydb["questionnaire6"]  # 存储随访问卷


mycol11 = mydb["questionnaire11"]  # 草稿箱中的脑出血患者调查问卷存储
mycol12 = mydb["questionnaire12"]  # 草稿箱中的健康人群调查问卷存储
mycol14 = mydb["questionnaire14"]  # 草稿箱中的健康人群调查问卷(体检中心)存储
mycol15 = mydb["questionnaire15"]  # 草稿箱中的脑出血患者调查问卷(医院)存储
mycol16 = mydb["questionnaire16"]  # 草稿箱中的随访问卷存储


#mycol3 = mydb["fabing"]
#mycol4 = mydb["siwang"]

@login_required
def naochuxue_result(request):
    return render(request, 'wenjuanresult/similar_table.html')


@login_required
def totalstatistics(request):
    return render(request, 'wenjuanresult/total_statistics.html')


@login_required
def countrate(request):
    return render(request, 'wenjuanresult/count_rate.html')


@login_required
def wenjuanNum(request):
    quest1 = mycol1.find().count()  # 脑出血患者调查问卷
    quest2 = mycol2.find().count()  # 健康人群调查问卷
    quest4 = mycol4.find().count()  # 健康人群调查问卷(体检中心)
    quest5 = mycol5.find().count()  # 脑出血患者调查问卷(医院)
    quest6 = mycol6.find().count()  # 随访问卷
    sheng = ["湖南省", "安徽省", "湖北省", "江西省", "河南省"]
    shengCount = []
    for i in sheng:
        Num = 0
        Num += mycol1.find({"所在的省": i}).count()
        Num += mycol2.find({"所在的省": i}).count()
        Num += mycol4.find({"所在的省": i}).count()
        Num += mycol5.find({"所在的省": i}).count()
        Num += mycol6.find({"所在的省": i}).count()
        shengCount.append(Num)
    wenjuancount = [quest1, quest2, quest4, quest5, quest6]  # 所有问卷对应数目
    return render(request, 'wenjuanresult/wenjuanNum_total_statistics.html',
                  {'wenjuancont': wenjuancount, 'shengCount': shengCount})


def wenjuanNum_check(request):
    if request.POST:
        sheng = request.POST.get("sheng")
        print(sheng)
    else:
        sheng = "总统计"
    if sheng == "总统计":
        return HttpResponse(request)
    else:
        ncx_pass = mycol1.find({"所在的省": sheng, '审核是否通过': '是'}).count()
        ncx_back = mycol11.find({"所在的省": sheng, '是否需要再次编辑': None}).count() + mycol11.find(
            {"所在的省": sheng, '是否需要再次编辑': '是'}).count()
        ncx_obj = mycol1.find({"所在的省": sheng, '审核是否通过': None}).count()

        jiankang_pass = mycol2.find({"所在的省": sheng, '审核是否通过': '是'}).count()
        jiankang_back = mycol12.find({"所在的省": sheng, '是否需要再次编辑': None}).count() + mycol12.find(
            {"所在的省": sheng, '是否需要再次编辑': '是'}).count()
        jiankang_obj = mycol2.find({"所在的省": sheng, '审核是否通过': None}).count()

        ncxyy_pass = mycol5.find({"所在的省": sheng, '审核是否通过': '是'}).count()
        ncxyy_back = mycol15.find({"所在的省": sheng, '是否需要再次编辑': None}).count() + mycol15.find(
            {"所在的省": sheng, '是否需要再次编辑': '是'}).count()
        ncxyy_obj = mycol5.find({"所在的省": sheng, '审核是否通过': None}).count()

        jiankangtj_pass = mycol4.find({"所在的省": sheng, '审核是否通过': '是'}).count()
        jiankangtj_back = mycol14.find({"所在的省": sheng, '是否需要再次编辑': None}).count() + mycol14.find(
            {"所在的省": sheng, '是否需要再次编辑': '是'}).count()
        jiankangtj_obj = mycol4.find({"所在的省": sheng, '审核是否通过': None}).count()

        suifang_pass = mycol6.find({"所在的省": sheng, '审核是否通过': '是'}).count()
        suifang_back = mycol16.find({"所在的省": sheng, '是否需要再次编辑': None}).count() + mycol16.find(
            {"所在的省": sheng, '是否需要再次编辑': '是'}).count()
        suifang_obj = mycol6.find({"所在的省": sheng, '审核是否通过': None}).count()

        y1 = [ncx_back, jiankang_back, ncxyy_back,
              jiankangtj_back, suifang_back]  # 待修改
        y2 = [ncx_obj, jiankang_obj, ncxyy_obj,
              jiankangtj_obj, suifang_obj]  # 未审核
        y3 = [ncx_pass, jiankang_pass, ncxyy_pass,
              jiankangtj_pass, suifang_pass]  # 审核通过
        wenjuancount = {"y1": y1, "y2": y2, "y3": y3}
        return HttpResponse(json.dumps(wenjuancount, ensure_ascii=False))


'''
    根据传入的问卷名返回对应的表名
    后续脑卒中问卷展示界面需要增加问卷时可以直接修改本函数
'''


def get_questionnaires(name):
    mycol = None
    cgx_mycol = None

    if ("入户筛查表" == name):
        mycol = mydb["questionnaire7"]
        cgx_mycol = mydb["questionnaire17"]

    return (mycol, cgx_mycol)


'''
	查看的前提是超级管理员
'''


def nzzNum(request):
    if request.user.is_superuser:
        return render(request, 'wenjuanresult/nzzNum_total_statistics.html')
    else:
        raise Http404


def nzzNum_check(request):
    questionnaire = request.POST.get('questionnaire')  # 问卷名称
    city = request.POST.get('city')  # 市
    mycol, mycol_cgx = get_questionnaires(questionnaire)

    nzz_obj = mycol.find({'所在的市': city})
    nzz_cgx_obj = mycol_cgx.find({'所在的市': city})

    region = []  # 存储所有的区域
    y1 = []  # 分别存储三种情况的问卷
    y2 = []
    y3 = []

    for i in nzz_obj:
        if i['所在的村或社区'] not in region:
            region.append(i['所在的村或社区'])

    for i in nzz_cgx_obj:
        if i['所在的村或社区'] not in region:
            region.append(i['所在的村或社区'])

    for tmp_region in region:
        nzz_pass = mycol.find({"所在的村或社区": tmp_region, '审核是否通过': '是'}).count()
        nzz_back = mycol_cgx.find({"所在的村或社区": tmp_region, '是否需要再次编辑': None}).count() + mycol_cgx.find(
            {"所在的村或社区": tmp_region, '是否需要再次编辑': '是'}).count()
        nzz_obj = mycol.find({"所在的村或社区": tmp_region, '审核是否通过': None}).count()

        y1.append(nzz_back)
        y2.append(nzz_obj)
        y3.append(nzz_pass)

    result = {"y1": y1, "y2": y2, "y3": y3, "region": region}

    return HttpResponse(json.dumps(result))  # 返回请求，发送数据


# 返回特定区域的问卷
# 后续需要增加问卷的话需要在questionnaires中增加问卷名字、同时还要修改get_questionnaires函数
def get_region_questionnaires(request):
    region = request.POST.get('region')  # 问卷名称
    y1 = []  # 存储入户筛查表
    y2 = []
    y3 = []
    questionnaires = ["入户筛查表"]

    for name in questionnaires:
        mycol, mycol_cgx = get_questionnaires(name)

        nzz_pass = mycol.find({"所在的村或社区": region, '审核是否通过': '是'}).count()
        nzz_back = mycol_cgx.find({"所在的村或社区": region, '是否需要再次编辑': None}).count() + mycol_cgx.find(
            {"所在的村或社区": region, '是否需要再次编辑': '是'}).count()
        nzz_obj = mycol.find({"所在的村或社区": region, '审核是否通过': None}).count()

        y1.append(nzz_back)
        y2.append(nzz_obj)
        y3.append(nzz_pass)

    result = {"y1": y1, "y2": y2, "y3": y3, "questionnaires": questionnaires}
    return HttpResponse(json.dumps(result))


def upload(request):
    if request:
        the_file = request.FILES.get("file", None)  # 获得上传的文件名
        # print("the_file:--",the_file)
        sheng = request.POST.get("sheng")  # 获得省份
        f = the_file.read()
        data = xlrd.open_workbook(file_contents=f)  # 打开excel读取数据
        names = data.sheet_names()  # 返回表格中所有工作表的名字(excel左下角那个)
        # print("names:--",names)
        status = data.sheet_loaded(names[0])  # 检查某个sheet是否导入完毕(左下角)
        if status is True:  # 导入完毕
            table = data.sheet_by_name(names[0])  # 通过名称获取sheet表
            keys = table.row_values(0)  # 第一行作为key值
            # print("keys:",keys)
            if keys:
                rowNum = table.nrows  # 获取该sheet中的有效行数
                colNum = table.ncols  # 获取该sheet中的有效列数
                # print('row',rowNum)
                #print('col', colNum)
                count = 0
                for i in range(2, rowNum):  # 从第三行（数据行）开始取数据(excel的特点)
                    # table.row_values(行数)：返回该行左右数据组成的列表
                    # 这行数据脑出血编号不为空并且是2类型
                    if table.row_values(i)[13] != '' and int(table.row_values(i)[13]) == 2:
                        count = count + 1
                    sheet_data = {"统计的省份": sheng}  # 定义一个字典用来存放对应数据
                    for j in range(0, colNum):  # 遍历每一行的各列
                        # print(keys[j],table.row_values(i)[j])
                        sheet_data[keys[j]] = table.row_values(
                            i)[j]  # 把第i行第j列的值取出赋给第j列的键值，构成字典
                        # print(sheet_data)
                    # print(sheet_data)
                    # mycol3.insert(sheet_data)   #导入数据库，数据清洗定位！！！
        return HttpResponse(json.dumps({"rownum": rowNum, "count": count}))


def upload2(request):
    if request:
        the_file = request.FILES.get("file", None)
        sheng = request.POST.get("sheng", None)
        #print('hhbb;', sheng)
        f = the_file.read()
        data = xlrd.open_workbook(file_contents=f)
        names = data.sheet_names()  # 返回表格中所有工作表的名字
        # print(names)
        status = data.sheet_loaded(names[0])
        keyslist = ["序号", "编号", "姓名", "联系人电话", "身份证号码",
                    "发病年月", "生存", "脑出血", "其他", "不知道", "死亡日期"]
        if status is True:
            table = data.sheet_by_name(names[0])
            keys = table.row_values(0)  # 第一行作为key值
            if keys:
                rowNum = table.nrows  # 获取该sheet中的有效行数
                colNum = table.ncols  # 获取该sheet中的有效列数
                # print('row',rowNum)
                #print('col', colNum)
                aimdeath = 0
                live = 0
                result = []  # 列表L存放取出的数据
                for i in range(3, rowNum):  # 从第三行（数据行）开始取数据
                    if table.row_values(i)[7] != '' and int(table.row_values(i)[7]) == 1:
                        aimdeath = aimdeath+1
                    if table.row_values(i)[6] != '' and int(table.row_values(i)[6]) == 1:
                        live = live+1
                    sheet_data = {"统计的省份": sheng}  # 定义一个字典用来存放对应数据
                    for j in range(0, colNum-1):
                        # print(keys[j],table.row_values(i)[j])
                        sheet_data[keyslist[j]] = table.row_values(
                            i)[j]  # 把第i行第j列的值取出赋给第j列的键值，构成字典
                        # print(sheet_data)
                    # print(sheet_data)
                    # mycol4.insert(sheet_data)    #导入数据库
                # print(aimdeath)
        return HttpResponse(json.dumps({"rownum": rowNum-live, "count": aimdeath}))


# 计算欧几里得距离
def distEclud(vecA, vecB):
    return sqrt(sum(power(vecA - vecB, 2)))  # 求两个向量之间的距离

# 构建聚簇中心，取k个(此例中为4)随机质心


def randCent(dataSet, k):
    n = shape(dataSet)[1]
    centroids = mat(zeros((k, n)))   # 每个质心有n个坐标值，总共要k个质心
    for j in range(n):
        minJ = min(dataSet[:, j])
        maxJ = max(dataSet[:, j])
        rangeJ = float(maxJ - minJ)
        centroids[:, j] = minJ + rangeJ * random.rand(k, 1)
    return centroids

# k-means 聚类算法


def kMeans(dataSet, k, distMeans=distEclud, createCent=randCent):
    m = shape(dataSet)[0]
    clusterAssment = mat(zeros((m, 2)))    # 用于存放该样本属于哪类及质心距离
    centroids = createCent(dataSet, k)
    clusterChanged = True   # 用来判断聚类是否已经收敛
    while clusterChanged:
        clusterChanged = False
        for i in range(m):  # 把每一个数据点划分到离它最近的中心点
            minDist = inf
            minIndex = -1
            for j in range(k):
                distcu = distMeans(centroids[j, :], dataSet[i, :])
                if distcu < minDist:
                    minDist = distcu
                    minIndex = j  # 如果第i个数据点到第j个中心点更近，则将i归属为j
            if clusterAssment[i, 0] != minIndex:
                clusterChanged = True  # 如果分配发生变化，则需要继续迭代
            clusterAssment[i, :] = minIndex, minDist**2   # 并将第i个数据点的分配情况存入字典
        print(centroids)
        for cent in range(k):   # 重新计算中心点
            ptsInClust = dataSet[nonzero(clusterAssment[:, 0].A == cent)[
                0]]   # 去第一列等于cent的所有列
            centroids[cent, :] = mean(ptsInClust, axis=0)  # 算出这些数据的中心点
    return centroids, clusterAssment


def trans_sex(sel):  # 性别
    if sel == '男':
        return 66 + random.uniform(-0.49, 0.49)
    else:
        return 33 + random.uniform(-0.49, 0.49)


def trans_age(sel):  # 计算年龄，根据身份证
    nowyear = datetime.datetime.now().year
    selyear = sel[6:10]
    return float(nowyear-int(selyear)) + random.uniform(-0.49, 0.49)


def trans_age2(sel):  # 计算年龄，根据出生日期
    nowyear = datetime.datetime.now().year
    selyear = sel[0]
    selyear = selyear[0:4]
    # print(selyear)
    return float(nowyear-int(selyear)) + random.uniform(-0.49, 0.49)


def trans_hunyin(sel):
    if sel == '丧偶':
        return 80 + random.uniform(-0.49, 0.49)
    elif sel == '离婚':
        return 60 + random.uniform(-0.49, 0.49)
    elif sel == '已婚':
        return 40 + random.uniform(-0.49, 0.49)
    elif sel == '未婚':
        return 20 + random.uniform(-0.49, 0.49)
    else:
        return 0 + random.uniform(-0.49, 0.49)


def trans_zhenduan(sel):  # 是否为脑出血
    if sel == '是':
        return 66 + random.uniform(-0.49, 0.49)
    else:
        return 33 + random.uniform(-0.49, 0.49)

# 首次被诊断的时间


def trans_fabing(sel):  # 发病次数
    if sel == '1次':
        return 10+random.uniform(0, 0.49)
    else:
        if sel == '10次及以上':
            return 100+random.uniform(-0.49, 0)
        else:
            if sel == '2次':
                return 20+random.uniform(-0.49, 0.49)
            if sel == '3次':
                return 30+random.uniform(-0.49, 0.49)
            if sel == '4次':
                return 40+random.uniform(-0.49, 0.49)
            if sel == '5次':
                return 50+random.uniform(-0.49, 0.49)
            if sel == '6次':
                return 60+random.uniform(-0.49, 0.49)
            if sel == '7次':
                return 70+random.uniform(-0.49, 0.49)
            if sel == '8次':
                return 80+random.uniform(-0.49, 0.49)
            if sel == '9次':
                return 90+random.uniform(-0.49, 0.49)

# 最近一次发病时间   #最近一次复发时间


def trans_fabingdate(sel):
    nowyear = datetime.datetime.now().year
    nowmonth = datetime.datetime.now().month
    if len(sel) > 7:
        selyear = int(sel[0:4])
        selmonth = int(sel[5:7])
        return abs((nowyear-selyear)*12+(nowmonth-selmonth)*1) + random.uniform(-0.49, 0.49)
    else:
        return 0

# def trans_qinshu(sel):   #亲属患病
#	for i in sel:
#		if i== '父亲':


def trans_ctmri(sel):  # 是否做ct检查 and 是否做mri检查
    if sel == '是':
        return 66 + random.uniform(-0.49, 0.49)
    else:
        if sel == '否':
            return 33 + random.uniform(-0.49, 0.49)
        else:
            return 0 + random.uniform(0, 0.49)


def trans_now(sel):  # 目前生存状态
    if sel == '脑出血急性期':
        return 20 + random.uniform(-0.49, 0.49)
    else:
        if sel == '脑出血恢复期':
            return 40 + random.uniform(-0.49, 0.49)
        else:
            if sel == '脑出血后遗症期':
                return 60 + random.uniform(-0.49, 0.49)
            else:
                return 80 + random.uniform(-0.49, 0.49)


def trans_bmi(sel1, sel2):  # 身高体重
    if sel1 != 0:
        return sel2/(sel1*sel1*0.0001)
    else:
        return 0


def trans_minzu(sel):  # 民族
    if sel == '汉族':
        return 66 + random.uniform(-0.49, 0.49)
    else:
        if sel == '少数民族':
            return 33 + random.uniform(-0.49, 0.49)
        else:
            return 0 + random.uniform(0, 0.49)

# 地址


def trans_edu(sel):  # 文化程度
    if sel == '大学本、专科或以上':
        return 90 + random.uniform(-0.49, 0.49)
    else:
        if sel == '文盲':
            return 30 + random.uniform(-0.49, 0.49)
        else:
            if sel == '小学':
                return 45 + random.uniform(-0.49, 0.49)
            else:
                if sel == '初中':
                    return 60 + random.uniform(-0.49, 0.49)
                else:
                    if sel == '高中（包括中专）':
                        return 75 + random.uniform(-0.49, 0.49)
                    else:
                        return 15 + random.uniform(-0.49, 0.49)


def trans_job(sel):  # 职业  13个  0,8,16,24,32,40,48,56,64,72,80,88,96
    if sel == '国家公务员':
        return 96 + random.uniform(-0.49, 0.49)
    else:
        if sel == '专业技术人员':
            return 88 + random.uniform(-0.49, 0.49)
        else:
            if sel == '职员':
                return 80 + random.uniform(-0.49, 0.49)
            else:
                if sel == '企业管理人员':
                    return 72 + random.uniform(-0.49, 0.49)
                else:
                    if sel == '工人':
                        return 64 + random.uniform(-0.49, 0.49)
                    else:
                        if sel == '农民':
                            return 56 + random.uniform(-0.49, 0.49)
                        else:
                            if sel == '学生':
                                return 48 + random.uniform(-0.49, 0.49)
                            else:
                                if sel == '现役军人':
                                    return 40 + random.uniform(-0.49, 0.49)
                                else:
                                    if sel == '自由职业者':
                                        return 32 + random.uniform(-0.49, 0.49)
                                    else:
                                        if sel == '个体经营者':
                                            return 24 + random.uniform(-0.49, 0.49)
                                        else:
                                            if sel == '无业人员':
                                                return 16 + random.uniform(-0.49, 0.49)
                                            else:
                                                if sel == '离（退）休人员':
                                                    return 8 + random.uniform(-0.49, 0.49)
                                                else:
                                                    return 0 + random.uniform(0, 0.49)


def trans_smokeage(sel):  # 烟龄  和饮酒龄 和戒酒龄
    return sel+random.uniform(-0.49, 0.49)


def trans_pasvsmo(sel):  # 是否被动吸烟
    if sel == '是':
        return 66 + random.uniform(-0.49, 0.49)
    else:
        if sel == '否':
            return 33 + random.uniform(-0.49, 0.49)
        else:
            return 0 + random.uniform(0, 0.49)


def trans_acti(sel):  # 体力活动
    if sel == '重度':
        return 66 + random.uniform(-0.49, 0.49)
    else:
        if sel == '中度':
            return 33 + random.uniform(-0.49, 0.49)
        else:
            return 0 + random.uniform(0, 0.49)


def trans_sleeptime(sel):  # 几点睡觉
    if sel == '10点前':
        return 20 + random.uniform(-0.49, 0.49)
    else:
        if sel == '10-11点前':
            return 40 + random.uniform(-0.49, 0.49)
        else:
            if sel == '11-12点前':
                return 60 + random.uniform(-0.49, 0.49)
            else:
                return 80 + random.uniform(-0.49, 0.49)


def trans_sleep(sel):  # 睡眠时间
    if sel == '4小时及4小时以下':
        return 10 + random.uniform(-0.49, 0.49)
    elif sel == '5小时':
        return 25 + random.uniform(-0.49, 0.49)
    elif sel == '6小时':
        return 35 + random.uniform(-0.49, 0.49)
    elif sel == '7小时':
        return 45 + random.uniform(-0.49, 0.49)
    elif sel == '8小时':
        return 55 + random.uniform(-0.49, 0.49)
    elif sel == '9小时':
        return 65 + random.uniform(-0.49, 0.49)
    else:
        return 80 + random.uniform(-0.49, 0.49)

# 首次脑梗死发病时间
# fabingdate()


def trans_kangxuemed(sel1):  # 是否规律服用抗血小板聚集药物,前者为是否，后者为药物类型
    if sel1 == '是':
        return 66 + random.uniform(-0.49, 0.49)
    else:
        if sel1 == '否':
            return 33 + random.uniform(-0.49, 0.49)
        else:
            return 0 + random.uniform(-0.49, 0.49)


def trans_hypertension(sel2):  # 有无高血压病史和年限

    return float(sel2) + random.uniform(-0.49, 0.49)

# 最高血压

# 血压控制范围


def trans_jiangya(sel):  # 降压药   #夜间睡觉是否打呼噜
    if sel == '是':
        return 66 + random.uniform(-0.49, 0.49)
    else:
        return 33 + random.uniform(-0.49, 0.49)


def trans_xuezhi(sel):  # 血脂范围   #血糖范围
    if sel == '偏高':
        return 80 + random.uniform(-0.49, 0.49)
    else:
        if sel == '偏低':
            return 60 + random.uniform(-0.49, 0.49)
        else:
            if sel == '正常':
                return 40 + random.uniform(-0.49, 0.49)
            else:
                return 20 + random.uniform(-0.49, 0.49)


def trans_tiaozhimed(sel1, sel2):  # 是否规律服用调脂药,前者为是否，后者为药物类型
    if sel1 == '是':
        if sel2 == '他汀类':
            return 90 + random.uniform(-0.49, 0.49)
        else:
            if sel2 == '其他':
                return 70 + random.uniform(-0.49, 0.49)
            else:
                return 50 + random.uniform(-0.49, 0.49)
    else:
        if sel1 == '否':
            return 33 + random.uniform(-0.49, 0.49)
        else:
            return 0 + random.uniform(0, 0.49)


def trans_nowxz(sel):  # 目前血脂是否正常  #是否规律服用降糖药  #是否使用胰岛素
    if sel == '是':
        return 66 + random.uniform(-0.49, 0.49)
    else:
        if sel == '否':
            return 33 + random.uniform(-0.49, 0.49)
        else:
            return 0 + random.uniform(0, 0.49)

# 血糖控制范围


def trans_tangniaomed(sel1, sel2):  # 是否存在糖尿病慢性并发症，后者为并发症类型
    if sel1 == '是':
        if sel2 == '糖尿病肾病':
            return 90 + random.uniform(-0.49, 0.49)
        else:
            if sel2 == '糖尿病眼部并发症':
                return 80 + random.uniform(-0.49, 0.49)
            else:
                if sel2 == '糖尿病足':
                    return 70 + random.uniform(-0.49, 0.49)
                else:
                    if sel2 == '糖尿病周围神经病变':
                        return 60 + random.uniform(-0.49, 0.49)
                    else:
                        if sel2 == '其他':
                            return 50 + random.uniform(-0.49, 0.49)
                        else:
                            return 40 + random.uniform(-0.49, 0.49)
    else:
        if sel1 == '否':
            return 23 + random.uniform(-0.49, 0.49)
        else:
            return 0 + random.uniform(0, 0.49)


def trans_fangchan(sel):  # 心房颤动病史
    if sel == '有':
        return 66 + random.uniform(-0.49, 0.49)
    else:
        if sel == '无':
            return 33 + random.uniform(-0.49, 0.49)
        else:
            return 0 + random.uniform(0, 0.49)


def trans_kangning(sel2):  # 是否规律服用抗凝药物
    return float(sel2) + random.uniform(-0.49, 0.49)


def trans_guanxin(sel1, sel2):  # 冠心病病史，且有无规律服用药物
    if sel1 == '有':
        if sel2 == '是':
            return 80 + random.uniform(-0.49, 0.49)
        else:
            return 60 + random.uniform(-0.49, 0.49)
    else:
        if sel1 == '无':
            return 33 + random.uniform(-0.49, 0.49)
        else:
            return 0 + random.uniform(0, 0.49)


def transall(tedata):
    if '患者性别' in tedata:
        tedata['患者性别'] = trans_sex(tedata['患者性别'])
    if '患者年龄' not in tedata or (tedata['患者年龄'] >= u'\u4e00' and tedata['患者年龄'] <= u'\u9fff'):
        if '患者身份证号码' in tedata:
            tedata['患者年龄'] = trans_age(tedata['患者身份证号码'])
            if tedata['患者年龄'] < 0 or tedata['患者年龄'] > 120:
                tedata['患者年龄'] = trans_age2([tedata['患者出生日期']])
        else:
            tedata['患者年龄'] = -1
    else:
        tedata['患者年龄'] = float(tedata['患者年龄'])
    if '婚姻' in tedata:
        tedata['婚姻'] = trans_hunyin(tedata['婚姻'])
    if '是否被医生诊断为脑出血' in tedata:
        tedata['是否被医生诊断为脑出血'] = trans_zhenduan(tedata['是否被医生诊断为脑出血'])
        if '首次被确诊为脑出血的时间' in tedata:
            if tedata['首次被确诊为脑出血的时间'] != '':
                tedata['首次被确诊为脑出血的时间'] = trans_fabingdate(
                    tedata['首次被确诊为脑出血的时间'])/2
            else:
                tedata['最近一次发病时间'] = 0
        else:
            tedata['首次被确诊为脑出血的时间'] = 0

    if '脑出血是否复发' in tedata:
        if tedata['脑出血是否复发'] == '是':
            tedata['发病次数'] = trans_fabing(tedata['发病次数'])
            if '最近一次发病时间' in tedata:
                if tedata['最近一次发病时间'] != '':
                    tedata['最近一次发病时间'] = trans_fabingdate(tedata['最近一次发病时间'])
                else:
                    tedata['最近一次发病时间'] = 0
        else:
            tedata['发病次数'] = 0
            tedata['最近一次发病时间'] = 0
    if '脑出血发病时是否做CT/CTA检查' in tedata:
        tedata['脑出血发病时是否做CT/CTA检查'] = trans_ctmri(tedata['脑出血发病时是否做CT/CTA检查'])
    if '脑出血发病时是否做磁共振(MRI)检查' in tedata:
        tedata['脑出血发病时是否做磁共振(MRI)检查'] = trans_ctmri(
            tedata['脑出血发病时是否做磁共振(MRI)检查'])
    if '患者目前生存状态' in tedata:
        tedata['患者目前生存状态'] = trans_now(tedata['患者目前生存状态'])
    if '身高（cm）' in tedata:
        if '体重（kg）' in tedata:
            tedata['BMI'] = trans_bmi(tedata['身高（cm）'], tedata['体重（kg）'])
            if tedata['BMI'] > 50 or tedata['BMI'] < 10:
                tedata['BMI'] = 23.9
    if '民族' in tedata:
        tedata['民族'] = trans_minzu(tedata['民族'])
    if '文化程度' in tedata:
        tedata['文化程度'] = trans_edu(tedata['文化程度'])
    if '职业' in tedata:
        tedata['职业'] = trans_job(tedata['职业'])
    if '吸烟史' in tedata:
        if tedata['吸烟史'] == '有':
            tedata['烟龄'] = trans_smokeage(tedata['烟龄'])
        else:
            tedata['烟龄'] = 0
            tedata['已戒烟多少年'] = 0
        tedata['吸烟史'] = trans_fangchan(tedata['吸烟史'])
    if '是否被动吸烟' in tedata:
        tedata['是否被动吸烟'] = trans_pasvsmo(tedata['是否被动吸烟'])
    if '发病前是否戒烟' in tedata:
        if tedata['发病前是否戒烟'] == '是':
            tedata['已戒烟多少年'] = trans_smokeage(tedata['已戒烟多少年'])
        else:
            tedata['已戒烟多少年'] = 0
    if '是否被动吸烟' in tedata:
        tedata['是否被动吸烟'] = trans_pasvsmo(tedata['是否被动吸烟'])

    if '饮酒史' in tedata:
        if tedata['饮酒史'] == '有':
            tedata['酒龄'] = trans_smokeage(tedata['酒龄'])
        else:
            tedata['酒龄'] = 0
            tedata['已戒酒多少年'] = 0
        tedata['饮酒史'] = trans_fangchan(tedata['饮酒史'])
    if '发病前是否戒酒' in tedata:
        if tedata['发病前是否戒酒'] == '是':
            tedata['已戒酒多少年'] = trans_smokeage(tedata['已戒酒多少年'])
        else:
            tedata['已戒酒多少年'] = 0
    if '体力活动' in tedata:
        tedata['体力活动'] = trans_acti(tedata['体力活动'])
    if '晚上一般几点睡觉' in tedata:
        tedata['晚上一般几点睡觉'] = trans_sleep(tedata['晚上一般几点睡觉'])
    if '晚上一般睡眠时长' in tedata:
        tedata['晚上一般睡眠时长'] = trans_sleeptime(tedata['晚上一般睡眠时长'])
    if '脑出血发病以前是否有过脑梗死' in tedata:
        if tedata['脑出血发病以前是否有过脑梗死'] == '是':
            if tedata['首次脑梗死发病时间'] != '':
                tedata['首次脑梗死发病时间'] = trans_fabingdate(tedata['首次脑梗死发病时间'])/2
            else:
                tedata['首次脑梗死发病时间'] = 0
            tedata['是否规律服用抗血小板聚集药物'] = trans_kangxuemed(
                tedata['是否规律服用抗血小板聚集药物'])
        else:
            tedata['首次脑梗死发病时间'] = 0
            tedata['是否规律服用抗血小板聚集药物'] = 0
        tedata['脑出血发病以前是否有过脑梗死'] = trans_kangxuemed(tedata['脑出血发病以前是否有过脑梗死'])
    # if tedata['是否知道自己的血压'] == '是' and tedata['既往有无高血压病史'] == '有':
    #	tedata['高血压病史年限'] = trans_hypertension(tedata['高血压病史年限'])
    #	tedata['是否规律服用降压药'] = trans_jiangya(tedata['是否规律服用降压药'])
    # else:
    #	tedata['高血压病史年限'] = 0
    #	tedata['是否规律服用降压药'] = 0
    if '是否知道自己的血压' in tedata:
        if tedata['是否知道自己的血压'] == '是':
            if tedata['既往有无高血压病史'] == '有':
                tedata['是否规律服用降压药'] = trans_nowxz(tedata['是否规律服用降压药'])
            tedata['既往有无高血压病史'] = trans_fangchan(['既往有无高血压病史'])
    if '是否测量过血脂' in tedata:
        if tedata['是否测量过血脂'] == '是':
            if tedata['血脂范围'] == '偏高':
                tedata['目前血脂是否正常'] = trans_nowxz(tedata['目前血脂是否正常'])
                tedata['是否规律服用调脂药'] = trans_nowxz(tedata['是否规律服用调脂药'])
            else:
                tedata['目前血脂是否正常'] = 66 + random.uniform(-0.49, 0.49)
                tedata['是否规律服用调脂药'] = 0
            tedata['血脂范围'] = trans_xuezhi(tedata['血脂范围'])
    else:
        tedata['血脂范围'] = 0
        tedata['是否规律服用调脂药'] = 0
        tedata['目前血脂是否正常'] = 66 + random.uniform(-0.49, 0.49)
    if '以前是否测量血糖' in tedata:
        if tedata['以前是否测量血糖'] == '是':
            if tedata['血糖范围'] == '偏高':
                tedata['是否规律服用降糖药'] = trans_nowxz(tedata['是否规律服用降糖药'])
                tedata['是否使用胰岛素'] = trans_nowxz(['是否使用胰岛素'])
            else:
                tedata['是否规律服用降糖药'] = 0
                tedata['是否使用胰岛素'] = 0
            tedata['血糖范围'] = trans_xuezhi(tedata['血糖范围'])
        else:
            tedata['血糖范围'] = 0
            tedata['是否规律服用降糖药'] = 0
            tedata['是否使用胰岛素'] = 0
    else:
        tedata['血糖范围'] = 0
        tedata['是否规律服用降糖药'] = 0
        tedata['是否使用胰岛素'] = 0
    if '心房颤动病史' in tedata:
        if tedata['心房颤动病史'] == '有':
            if '是否规律使用抗凝药物' in tedata:
                if tedata['是否规律使用抗凝药物'] == '是':
                    tedata['使用时长1'] = trans_kangning(tedata['使用时长1'])
                else:
                    tedata['使用时长1'] = 0
        else:
            tedata['使用时长1'] = 0
        tedata['心房颤动病史'] = trans_fangchan(tedata['心房颤动病史'])
    if '冠心病病史' in tedata:
        tedata['冠心病病史'] = trans_fangchan(tedata['冠心病病史'])
    if '夜间睡觉是否打呼噜' in tedata:
        tedata['夜间睡觉是否打呼噜'] = trans_jiangya(tedata['夜间睡觉是否打呼噜'])
    if '是否规律服用药物' not in tedata:
        tedata['是否规律服用药物'] = 0
    return tedata


def transjiankang(tedata):
    if '性别' in tedata:
        tedata['性别'] = trans_sex(tedata['性别'])
    if '年龄' not in tedata:
        if '身份证号码' in tedata:
            tedata['年龄'] = trans_age(tedata['身份证号码'])
            if tedata['年龄'] < 0 or tedata['年龄'] > 120:
                tedata['年龄'] = trans_age2([tedata['出生日期']])
        else:
            tedata['年龄'] = -1
    else:
        tedata['年龄'] = float(tedata['年龄'])

    if '身高（cm）' in tedata:
        if '体重（kg）' in tedata:
            tedata['BMI'] = trans_bmi(tedata['身高（cm）'], tedata['体重（kg）'])
            if tedata['BMI'] > 50 or tedata['BMI'] < 10:
                tedata['BMI'] = 23.9
    if '婚姻' in tedata:
        tedata['婚姻'] = trans_hunyin(tedata['婚姻'])
    if '文化程度' in tedata:
        tedata['文化程度'] = trans_edu(tedata['文化程度'])

    if '吸烟史' in tedata:
        tedata['吸烟史'] = trans_fangchan(tedata['吸烟史'])
    if '饮酒史' in tedata:
        tedata['饮酒史'] = trans_fangchan(tedata['饮酒史'])

    if '是否被动吸烟' in tedata:
        tedata['是否被动吸烟'] = trans_pasvsmo(tedata['是否被动吸烟'])

    if '体力活动' in tedata:
        tedata['体力活动'] = trans_acti(tedata['体力活动'])
    if '晚上一般几点睡觉' in tedata:
        tedata['晚上一般几点睡觉'] = trans_sleep(tedata['晚上一般几点睡觉'])
    if '晚上一般睡眠时长' in tedata:
        tedata['晚上一般睡眠时长'] = trans_sleeptime(tedata['晚上一般睡眠时长'])
    if '您是否有过脑梗死' in tedata:
        if tedata['您是否有过脑梗死'] == '是':
            tedata['您是否规律服用抗血小板聚集药物'] = trans_kangxuemed(
                tedata['您是否规律服用抗血小板聚集药物'])
        else:
            tedata['您是否规律服用抗血小板聚集药物'] = 0
        tedata['您是否有过脑梗死'] = trans_kangxuemed(tedata['您是否有过脑梗死'])

    # if tedata['是否知道自己的血压'] == '是' and tedata['既往有无高血压病史'] == '有':
    #	tedata['高血压病史年限'] = trans_hypertension(tedata['高血压病史年限'])
    #	tedata['是否规律服用降压药'] = trans_jiangya(tedata['是否规律服用降压药'])
    # else:
    #	tedata['高血压病史年限'] = 0
    #	tedata['是否规律服用降压药'] = 0
    if '您是否知道自己的血压' in tedata:
        if tedata['您是否知道自己的血压'] == '是':
            if tedata['既往有无高血压病史'] == '有':
                tedata['您是否规律服用降压药'] = trans_nowxz(tedata['您是否规律服用降压药'])
            tedata['既往有无高血压病史'] = trans_fangchan(['既往有无高血压病史'])
    if '您是否测量过血脂' in tedata:
        if tedata['您是否测量过血脂'] == '是':
            if tedata['血脂范围'] == '偏高':
                tedata['目前血脂是否正常'] = trans_nowxz(tedata['目前血脂是否正常'])
                tedata['您是否规律服用调脂药'] = trans_nowxz(tedata['您是否规律服用调脂药'])
            else:
                tedata['目前血脂是否正常'] = 66 + random.uniform(-0.49, 0.49)
                tedata['是否规律服用调脂药'] = 0
        else:
            tedata['是否规律服用调脂药'] = 0
            tedata['目前血脂是否正常'] = 66 + random.uniform(-0.49, 0.49)
    if '以前是否测量血糖' in tedata:
        if tedata['以前是否测量血糖'] == '是':
            if tedata['血糖范围'] == '偏高':
                tedata['您是否规律服用降糖药'] = trans_nowxz(tedata['您是否规律服用降糖药'])
                tedata['您是否使用胰岛素'] = trans_nowxz(['您是否使用胰岛素'])
            tedata['血糖范围'] = trans_xuezhi(tedata['血糖范围'])
        else:
            tedata['血糖范围'] = 0
            tedata['您是否规律服用降糖药'] = 0
            tedata['您是否使用胰岛素'] = 0
    else:
        tedata['血糖范围'] = 0
        tedata['您是否规律服用降糖药'] = 0
        tedata['您是否使用胰岛素'] = 0
    if '心房颤动病史' in tedata:
        tedata['心房颤动病史'] = trans_fangchan(tedata['心房颤动病史'])
    if '冠心病病史' in tedata:
        tedata['冠心病病史'] = trans_fangchan(tedata['冠心病病史'])
    if '夜间睡觉是否打呼噜' in tedata:
        tedata['夜间睡觉是否打呼噜'] = trans_jiangya(tedata['夜间睡觉是否打呼噜'])
    return tedata


@login_required
def julei_tables(request):  # 聚类图
    alldata = []
    allpoint = []
    ids = []
    tedata = []
    allitem = ["患者性别", "患者年龄", "BMI", "婚姻", "文化程度",
                       "吸烟史", "是否被动吸烟", "饮酒史", "体力活动", "晚上一般几点睡觉",
                       "晚上一般睡眠时长", "脑出血发病以前是否有过脑梗死", "是否规律服用抗血小板聚集药物",
                       "既往有无高血压病史", "是否规律服用降压药", "是否规律服用调脂药", "目前血脂是否正常",
                       "血糖范围", "是否规律服用降糖药", "是否使用胰岛素", "心房颤动病史", "冠心病病史", "夜间睡觉是否打呼噜"]
    jiankangitem = ["性别", "年龄", "BMI", "婚姻", "文化程度",
                    "吸烟史", "是否被动吸烟", "饮酒史", "体力活动", "晚上一般几点睡觉",
                    "晚上一般睡眠时长", "您是否有过脑梗死", "您是否规律服用抗血小板聚集药物",
                    "既往有无高血压病史", "您是否规律服用降压药", "您是否规律服用调脂药", "目前血脂是否正常",
                    "血糖范围", "您是否规律服用降糖药", "您是否使用胰岛素", "心房颤动病史", "冠心病病史", "夜间睡觉是否打呼噜"]
    if request.POST:
        sheng = request.POST.get('省')
        print(sheng)
        ids = []
        datas = []
        allpoint = []
        for tedata in mycol.find({"采样地址所在的省": sheng}):
            tedata = transall(tedata)
            ids.append(tedata['_id'])
            quanbu = []
            for i in allitem:
                if i not in tedata:
                    tedata[i] = 0
                if isinstance(tedata[i], str):
                    print(tedata[i])
                quanbu.append(tedata[i])
            #print(quanbu, ",")
            datas.append(quanbu)

        pca = PCA(n_components=2)  # 加载PCA算法，设置降维后主成分数目为2
        reduced_x = pca.fit_transform(datas)  # 对样本进行降维
        red_x, red_y = [], []

        for i in range(len(reduced_x)):
            temp = []
            red_x.append(reduced_x[i][0])
            red_y.append(reduced_x[i][1])
            temp.append(round(reduced_x[i][0], 2))
            temp.append(round(reduced_x[i][1], 2))
            allpoint.append(temp)
        datMat = mat(allpoint)
        myCentroids, clustAssing = kMeans(datMat, 4)
        # print(myCentroids)
        # print(clustAssing)
        newarray = clustAssing.A
        # print(type(newarray))
        # np.trunc(clustAssing[:,0])
        result0 = {}
        result1 = {}
        result2 = {}
        result3 = {}
        tempjuleipoint = {}
        for i in range(len(allpoint)):
            if int(clustAssing[i, 0]) == 0:
                result0[ids[i]] = allpoint[i]
            if int(clustAssing[i, 0]) == 1:
                result1[ids[i]] = allpoint[i]
            if int(clustAssing[i, 0]) == 2:
                result2[ids[i]] = allpoint[i]
            if int(clustAssing[i, 0]) == 3:
                result3[ids[i]] = allpoint[i]

    # 可视化
        #plt.scatter(red_x, red_y, c='r', marker='x')
        # plt.show()
    # print(allpoint[0])
    print(len(allpoint))
    return HttpResponse(json.dumps({"ids": ids, "allpoint": allpoint, "result0": result0, "result1": result1, "result2": result2, "result3": result3}))


@login_required
def see_tables(request):  # 脑出血患者问卷
    sheng = ""
    wenjuantype = ""
    y = []
    temp = []
    items = []
    test = {}
    x = {}
    alldata = []
    ids = []
    allout = {}
    shengfen = ['湖南省', '湖北省', '江西省', '河南省', '安徽省']
    if request.POST:
        sheng = request.POST.get('省')
        print(sheng)
        wenjuantype = request.POST.get('问卷类型')
        print(wenjuantype)
        items = request.POST.get('选项')
        itemsm = json.loads(items)
        # print(itemsm)

        maxnum = request.POST.get('maxnum')
        inputid = request.POST.get('inputid')
        allitem = ["患者性别", "发病次数", "是否被医生诊断为脑出血", "脑出血发病时是否做CT/CTA检查",
                           "脑出血发病时是否做磁共振(MRI)检查", "患者目前生存状态", "身高（cm）", "体重（kg）", "民族", "文化程度", "职业",
                           "烟龄", "已戒烟多少年", "是否被动吸烟", "酒龄", "已戒酒多少年", "体力活动"]
        if sheng in shengfen:
            alldata = []
            # testid = ["5d8ae161b3e82406e0b8fafe","5d90578db3e8241540b460a9","5d909009b3e8241540b460ad","5d8d6f05b3e82406e0b8fb1c",
            #	   "5d8d8786b3e82406e0b8fb1f","5d91741cb3e8241540b460af","5d917804b3e8241540b460b2"]
            ids = []

            if int(maxnum) > 1:
                ids = count_sim(inputid, itemsm, int(maxnum)-1, sheng)
            ids.append(inputid)
            #ids = [ "5dddd53cb3e8241540b4633f"]
            # print(ids)
            for mm in range(0, len(ids)):
                x = mycol.find_one({"采样地址所在的省": sheng, "_id": ids[mm]})
                part2 = mycol.find_one({"采样地址所在的省": sheng, "_id": ids[mm]})
                #tempall = mycol.find_one({"采样地址所在的省": "湖南省","_id":ObjectId(ids[mm])})
                # print(x)
                if x == None:
                    continue
                else:
                    x = transall(x)
                    # print(x)
                    del x['_id']
                    #temp = list(x.values())
                    #temp = list(map(float, temp))
                    # print(temp)
                    shuchu = []
                    part2shuchu = []
                    for i in itemsm:
                        if i not in x:
                            x[i] = 0
                        shuchu.append(x[i])
                    y.append(shuchu)
                    #del tempall['_id']
                    # alldata.append(list(tempall.values()))
                    # print(part2)
                    for i in allitem:
                        if i in part2:
                            part2shuchu.append(part2[i])
                        else:
                            # print(i)
                            part2[i] = "无"
                            part2shuchu.append(part2[i])
                    allout[ids[mm]] = part2shuchu
                    x = {}
    # print(alldata)
    return HttpResponse(json.dumps({"name": ids, "lines": y, "allout": allout}))


def count_sim(id, items, nums, sheng):
    tempxuanxiang = {}
    sim = {}
    dis = 0.0
    aim = mycol.find_one({"采样地址所在的省": sheng, "_id": id})
    aim = transall(aim)
    for xx in mycol.find({"采样地址所在的省": sheng}):
        if xx['_id'] != aim['_id']:
            xx = transall(xx)
            for i in items:
                # 欧式距离
                if i not in xx and i in aim:
                    xx[i] = 0
                if i not in aim and i in xx:
                    aim[i] = 0
                if i not in aim and i not in xx:
                    aim[i] = 0
                    xx[i] = 0
                tempdis = (float(xx[i])-float(aim[i])) * \
                    (float(xx[i])-float(aim[i]))

                dis += tempdis
            dis = math.sqrt(dis)
            sim[xx['_id']] = dis
    result = []
    last = []
    for k in sorted(sim, key=sim.__getitem__):
        result.append(k)
    minnum = min(int(nums), len(result))
    for i in range(minnum):
        last.append(result[i])
    # print(last)
    return last


def totalpost(request):

    if request.POST:
        typepost = request.POST.get('typepost')  # 获取前端发来的类别
        shengs = ['湖南省', '湖北省', '江西省', '河南省', '安徽省']  # 记录省的数组
        aimtips = {"性别": "性别", "体力活动": "体力活动", "脑出血发病时是否做CT/CTA检查": "脑出血发病时是否做CT/CTA检查",
                   "脑出血发病时是否做磁共振(MRI)检查": "脑出血发病时是否做磁共振(MRI)检查", "民族": "民族",
                   "文化程度": "文化程度", "职业": "职业", "患者目前生存状态": "患者目前生存状态", "是否被动吸烟": "是否被动吸烟",
                           "晚上一般几点睡觉": "晚上一般几点睡觉", "晚上一般睡眠时长": "晚上一般睡眠时长", "血脂范围": "血脂范围",
                           "血糖范围": "血糖范围", "心房颤动病史": "心房颤动病史", "夜间睡觉是否打呼噜": "夜间睡觉是否打呼噜", "是否住院治疗": "是否住院治疗",
                           "是否定起复诊": "患者是否定期复诊", "婚姻情况": "婚姻", "家庭人均月收入": "家庭人均月收入（子女及政府救助的也计算入内）",
                           "吸烟史": "吸烟史", "饮酒史": "饮酒史", "脑出血发病以前是否有过脑梗死": "脑出血发病以前是否有过脑梗死",
                           "有无高血压病史": "既往有无高血压病史", "心房颤动病史": "心房颤动病史", "冠心病病史": "冠心病病史", "夜间睡觉是否打呼噜": "夜间睡觉是否打呼噜",
                           "戒烟教育": "戒烟教育", "限酒教育": "限酒教育", "控制体重教育": "控制体重教育", "低盐饮食教育": "低盐饮食教育", "低脂饮食教育": "低脂饮食教育",
                           "糖尿病健康教育": "糖尿病健康教育", "大便": "大便", "小便": "小便", "梳洗": "梳洗", "如厕": "如厕", "吃饭": "吃饭", "转移": "转移", "活动": "活动",
                           "穿衣": "穿衣", "上楼梯": "上楼梯", "洗澡": "洗澡", "食用水产品频率": "食用水产品（包括鱼、虾、贝类、海带等）的频率是", "食用蔬菜的频率": "食用蔬菜的频率是",
                           "食用水果的频率": "食用水果的频率是", "食用奶及奶制品的频率": "食用奶及奶制品的频率是", "食用辣椒的频率": "食用辣椒的频率是",
                           "食用熏制食品的频率": "食用熏制食品（包括腊鱼、腊肉、熏豆腐干等）的频率是", "食用腌制食品的频率": "食用腌制食品（包括咸菜、坛子菜、腌制腊肉等）的频率是"}  # 前端发来的与数据库中的对应关系

        # 记录多选类型的数组
        multiple = {
            '口味偏好': ['嗜咸', '嗜甜', '嗜辣', '嗜酸', '口味偏油', '口味适中', '口味较淡'],
            '医保类型': ['城镇职工医保', '城镇居民/城乡居民医保', '新农合/城乡居民医保', '商业保险', '公费医疗', '自费', '其他'],
            '饮酒种类': ['白酒', '红酒', '啤酒', '米酒', '其他'],
            '用油种类': ['菜籽油', '花生油', '大豆油', '猪油', '其他']
        }
        # 记录多选类型在数据库中的对应
        multipleData = {
            '口味偏好': "膳食习惯（可多选）",
            '医保类型': "医保类型（可多选）",
            '饮酒种类': "饮酒种类（可多选）",
            '用油种类': "患者家庭使用的油为（可多选）"
        }

        # 记录数值范围的数组
        scope = {
            '烟龄': ['0~5年', '5~10年', '10~20年', '20~30年', '30~40年', '40年以上'],
            '酒龄': ['0~5年', '5~10年', '10~20年', '20~30年', '30~40年', '40年以上']
        }

        # 专门处理单选情况
        if typepost in aimtips.keys():  # 如果传来的类别存在
            shengresult = []
            zongresult = {}
            allvalue = {}
            for ss in shengs:  # 遍历各省名称
                sexdic = {}  # 用于存储每一种结果的数量
                shengresult = []
                # 查找到该省的所有typepost，例如查找到湖南省所有的患者性别{"患者性别":"男"}
                for i in mycol1.find({"所在的省": ss}, {"_id": 0, aimtips[typepost]: 1}):
                    if aimtips[typepost] in i:
                        # 记录typepost每一种结果的数量，如果该结果在sexdic中不存在，则创建并置1，否则意味着存在，即加一
                        if i[aimtips[typepost]] in sexdic:
                            sexdic[i[aimtips[typepost]]] += 1
                        else:
                            sexdic[i[aimtips[typepost]]] = 1
                # 至此，sexdic记录了各种每种结果及数量 例如{'男'：150,'女',120}
                # allvalue对应每种结果各省数量的总统计
                for te in sexdic.keys():  # 遍历每种结果
                    if te in allvalue:
                        allvalue[te] += sexdic[te]
                    else:
                        allvalue[te] = sexdic[te]
                # 至此，allvalue记录了5个省每种结果的总数量 例如：{'男': 1000,'女': 1200}

                # 改变格式，用shengresult接收各省新格式
                for i in sexdic.keys():
                    temp = {}
                    temp['name'] = i
                    temp['value'] = sexdic[i]
                    shengresult.append(temp)
                    # 至此，shengresult保存了该省每种结果的统计，例如：{{'name': '男','value': 150},{'name': '女' ,'value': 100}}
                # zongresult汇总各省结果统计 例如：{'湖南省': [{'name': '男', 'value': 122}, {'name': '女', 'value': 88}], '湖北省': [{'name': '男', 'value': 1}]}
                zongresult[ss] = shengresult

            # 将allvalue的数据改变为新格式，用shengreslut存储，注，这个shengresult和之前的不是一个东西
            shengresult = []
            for i in allvalue.keys():
                temp = {}
                temp['name'] = i
                temp['value'] = allvalue[i]
                shengresult.append(temp)
            # 抽离各省数据(数组类型)
            # [{'name': '男', 'value': 122}, {'name': '女', 'value': 88}]
            hunansex = zongresult["湖南省"]
            hubeisex = zongresult["湖北省"]
            jiangxisex = zongresult["江西省"]
            henansex = zongresult["河南省"]
            anhuisex = zongresult["安徽省"]

            return HttpResponse(json.dumps({"hunan": hunansex, "hubei": hubeisex,
                                            "jiangxi": jiangxisex, "henan": henansex, "anhui": anhuisex, "zongtongji": shengresult}))  # 返回请求，发送数据

        if typepost == '发病次数':

            xuanxiang = ['1次', '2次', '3次', '4次', '5次',
                         '6次', '7次', '8次', '9次', '10次及以上', '0次']
            sexvalue = [0]*11
            shengresult = []
            zongresult = {}
            allvalue = [0]*11
            for ss in shengs:
                sexvalue = [0] * 11
                shengresult = []
                for i in mycol1.find({"所在的省": ss}, {"_id": 0, "脑出血是否复发": 1, "发病次数": 1}):
                    # print(i)
                    if i['脑出血是否复发'] == '是':
                        sexvalue[xuanxiang.index(i['发病次数'])] += 1
                    else:
                        sexvalue[10] += 1
                for te in range(len(sexvalue)):
                    allvalue[te] += sexvalue[te]
                for i in range(len(xuanxiang)):
                    temp = {}
                    temp['name'] = xuanxiang[i]
                    temp['value'] = sexvalue[i]
                    shengresult.append(temp)
                zongresult[ss] = shengresult
            shengresult = []
            for i in range(len(xuanxiang)):
                temp = {}
                temp['name'] = xuanxiang[i]
                temp['value'] = allvalue[i]
                shengresult.append(temp)
            hunansex = zongresult["湖南省"]
            hubeisex = zongresult["湖北省"]
            jiangxisex = zongresult["江西省"]
            henansex = zongresult["河南省"]
            anhuisex = zongresult["安徽省"]
            # print(hunansex)
            return HttpResponse(json.dumps({"hunan": hunansex, "hubei": hubeisex,
                                            "jiangxi": jiangxisex, "henan": henansex, "anhui": anhuisex, "zongtongji": shengresult}))

        # 处理范围型计算
        if typepost == '年龄':
            xuanxiang = ['0~10岁', '11~20岁', '21~30岁', '31~40岁',
                         '41~50岁', '51~60岁', '61~70岁', '71~80岁', '80岁以上', ]
            sexvalue = [0]*11
            shengresult = []
            zongresult = {}
            allvalue = [0]*11
            nowyear = datetime.datetime.now().year
            for ss in shengs:
                sexvalue = [0] * 11
                shengresult = []
                for i in mycol1.find({"所在的省": ss}, {"_id": 0, "身份证号码": 1, "出生日期": 1, "患者年龄": 1}):
                    if '患者年龄' not in i or (i['患者年龄'] >= u'\u4e00' and i['患者年龄'] <= u'\u9fff'):
                        if '身份证号码' in i:
                            selyear = i['身份证号码']
                            selyear = selyear[6:10]
                            i['患者年龄'] = int(nowyear - int(selyear))
                            if i['患者年龄'] < 0 or i['患者年龄'] > 120:
                                print(i['身份证号码'])
                                i['患者年龄'] = trans_age2([i['出生日期']])
                        else:
                            i['患者年龄'] = -1
                    age = int(i['患者年龄'])
                    # print(age)
                    if age < 11:
                        sexvalue[0] += 1
                    elif age < 21:
                        sexvalue[1] += 1
                    elif age < 31:
                        sexvalue[2] += 1
                    elif age < 41:
                        sexvalue[3] += 1
                    elif age < 51:
                        sexvalue[4] += 1
                    elif age < 61:
                        sexvalue[5] += 1
                    elif age < 71:
                        sexvalue[6] += 1
                    elif age < 81:
                        sexvalue[7] += 1
                    else:
                        sexvalue[8] += 1

                for te in range(len(sexvalue)):
                    allvalue[te] += sexvalue[te]
                for i in range(len(xuanxiang)):
                    temp = {}
                    temp['name'] = xuanxiang[i]
                    temp['value'] = sexvalue[i]
                    shengresult.append(temp)
                zongresult[ss] = shengresult
            shengresult = []
            for i in range(len(xuanxiang)):
                temp = {}
                temp['name'] = xuanxiang[i]
                temp['value'] = allvalue[i]
                shengresult.append(temp)
            hunansex = zongresult["湖南省"]
            hubeisex = zongresult["湖北省"]
            jiangxisex = zongresult["江西省"]
            henansex = zongresult["河南省"]
            anhuisex = zongresult["安徽省"]
            return HttpResponse(json.dumps({"hunan": hunansex, "hubei": hubeisex,
                                            "jiangxi": jiangxisex, "henan": henansex, "anhui": anhuisex, "zongtongji": shengresult}))

        # 处理烟龄或者酒龄
        if typepost in scope.keys():
            scopeArray = scope[typepost]
            zong = {}
            zongcont = [0, 0, 0, 0, 0, 0]
            for ss in shengs:
                cont = [0, 0, 0, 0, 0, 0]
                num = []
                for i in mycol1.find({'所在的省': ss}, {"_id": 0, typepost: 1}):
                    if typepost in i:
                        if i[typepost] >= 0 and i[typepost] < 5:
                            cont[0] += 1
                        elif i[typepost] >= 5 and i[typepost] < 10:
                            cont[1] += 1
                        elif i[typepost] >= 10 and i[typepost] < 20:
                            cont[2] += 1
                        elif i[typepost] >= 20 and i[typepost] < 30:
                            cont[3] += 1
                        elif i[typepost] >= 30 and i[typepost] < 40:
                            cont[4] += 1
                        else:
                            cont[5] += 1

                for i in range(len(cont)):
                    # 记录总数量
                    zongcont[i] += cont[i]
                    # 计算各省数据
                    temp = {}
                    temp['name'] = scopeArray[i]
                    temp['value'] = cont[i]
                    num.append(temp)
                zong[ss] = num

            zongresult = []
            for i in range(len(scopeArray)):
                temp = {}
                temp['name'] = scopeArray[i]
                temp['value'] = zongcont[i]
                zongresult.append(temp)

            hunan = zong["湖南省"]
            hubei = zong["湖北省"]
            jiangxi = zong["江西省"]
            henan = zong["河南省"]
            anhui = zong["安徽省"]
            return HttpResponse(json.dumps({"hunan": hunan, "hubei": hubei,
                                            "jiangxi": jiangxi, "henan": henan, "anhui": anhui, "zongtongji": zongresult}))  # 返回请求，发送数据

        # 处理多选
        if typepost in multiple.keys():
            multArray = multiple[typepost]  # 获取当前的多选数组
            multData = multipleData[typepost]  # 获取当前多选数组在数据库中的名称
            zong = {}
            for ss in shengs:
                num = []
                for i in range(len(multArray)):
                    count = mycol1.find(
                        {multData: multArray[i], '所在的省': ss}).count()
                    temp = {}
                    temp['name'] = multArray[i]
                    temp['value'] = count
                    num.append(temp)
                zong[ss] = num

            zongresult = []
            for i in range(len(multArray)):
                count = mycol.find({multData: multArray[i]}).count()
                temp = {}
                temp['name'] = multArray[i]
                temp['value'] = count
                zongresult.append(temp)

            hunan = zong["湖南省"]
            hubei = zong["湖北省"]
            jiangxi = zong["江西省"]
            henan = zong["河南省"]
            anhui = zong["安徽省"]
            return HttpResponse(json.dumps({"hunan": hunan, "hubei": hubei,
                                            "jiangxi": jiangxi, "henan": henan, "anhui": anhui, "zongtongji": zongresult}))  # 返回请求，发送数据

# 根据指定的脑出血id的部分选项，去寻找这些选项相符合的健康人群的数据，并将所有选项显示在散点图中


def compare_table(request):
    allitem = ["患者性别", "患者年龄", "BMI", "婚姻", "文化程度",
                       "吸烟史", "是否被动吸烟", "饮酒史", "体力活动", "晚上一般几点睡觉",
                       "晚上一般睡眠时长", "脑出血发病以前是否有过脑梗死", "是否规律服用抗血小板聚集药物",
                       "既往有无高血压病史", "是否规律服用降压药", "是否规律服用调脂药", "目前血脂是否正常",
                       "血糖范围", "是否规律服用降糖药", "是否使用胰岛素", "心房颤动病史", "冠心病病史", "夜间睡觉是否打呼噜"]
    jiankangitem = ["性别", "年龄", "BMI", "婚姻", "文化程度",
                    "吸烟史", "是否被动吸烟", "饮酒史", "体力活动", "晚上一般几点睡觉",
                    "晚上一般睡眠时长", "您是否有过脑梗死", "您是否规律服用抗血小板聚集药物",
                    "既往有无高血压病史", "您是否规律服用降压药", "您是否规律服用调脂药", "目前血脂是否正常",
                    "血糖范围", "您是否规律服用降糖药", "您是否使用胰岛素", "心房颤动病史", "冠心病病史", "夜间睡觉是否打呼噜"]
    if request.POST:
        sheng = request.POST.get('省')
        items = request.POST.get('选项')
        aimid = request.POST.get('inputid')
        print(items)
        allitems = []
        jiankangitems = []
        items = json.loads(items)
        for i in items:
            allitems.append(i)
            jiankangitems.append(jiankangitem[allitem.index(i)])
        for i in allitem:
            if i not in items:
                allitems.append(i)
        for i in jiankangitem:
            if i not in jiankangitems:
                jiankangitems.append(i)
        print(jiankangitems)
        alldb = {}
        quanbudata = []
        ids = []
        for i in allitems:
            alldb[i] = 1
        aim = mycol1.find_one({"所在的省": sheng, "_id": aimid})
        aim = transall(aim)
        ids.append(aimid)
        tempdata = []
        for i in allitems:
            if i not in aim:
                aim[i] = 0
            tempdata.append(aim[i])
        quanbudata.append(tempdata)
        newitem = {}
        for i in range(len(items)):
            # print(i)
            # print(allitem.index(i))
            newitem[jiankangitem[allitem.index(items[i])]] = aim[items[i]]
        print(newitem)
        for findx in mycol2.find({"所在的省": sheng}):
            findx = transjiankang(findx)
            flag = 0
            for i in newitem.keys():
                if round(findx[i]) != round(newitem[i]):
                    flag = 1
                    break
            if flag == 0:
                tempdata = []
                for i in jiankangitems:
                    if i not in findx:
                        findx[i] = 0
                    tempdata.append(findx[i])
                quanbudata.append(tempdata)
                ids.append(findx['_id'])
            # print(findx)
    return HttpResponse(json.dumps({"name": ids, "xuanxiangs": allitems, "allout": quanbudata}))


Que7 = mydb["questionnaire7"]       
Que8 = mydb["questionnaire8"]       
Que9 = mydb["questionnaire9"]       
Que10 = mydb["questionnaire10"]       
Que11 = mydb["questionnaire011"]       
QueCgx7 = mydb["questionnaire17"]   
QueCgx8 = mydb["questionnaire18"]   
QueCgx9 = mydb["questionnaire19"]   
QueCgx10 = mydb["questionnaire110"]   
QueCgx11 = mydb["questionnaire111"]   

def queNum(request):
    return render(request, 'wenjuanresult/queNum.html')

def queNum_solve(request):
    if request.method == 'GET':
        # 获取前端提交上来的查询内容
        City = request.GET.get('City', None)
        Region = request.GET.get('Region', None)
        Towns = request.GET.get('Towns', None)
        if City and Region and Towns:
            adminArea = City + Region + Towns
            #print(adminArea)
            #获取目标区域账号
            users = UserInfo.objects.filter(Q(address__contains=adminArea))
            #记录搜索条件
            conditions1 = []
            conditions2 = []
            for user in users:
                condition1 = {"登录账号": user.username, '是否需要再次编辑':{'$exists':1}}
                condition2 = {"登录账号": user.username, "是否需要再次编辑":"否"}
                conditions1.append(condition1)
                conditions2.append(condition2)
            #获取总数据
            Que7Tianxie = QueCgx7.find({"$or":conditions1}).count()
            Que8Tianxie = QueCgx8.find({"$or":conditions1}).count()
            Que9Tianxie = QueCgx9.find({"$or":conditions1}).count()
            Que10Tianxie = QueCgx10.find({"$or":conditions1}).count()
            Que7Tijiao = QueCgx7.find({"$or":conditions2}).count()
            Que8Tijiao = QueCgx8.find({"$or":conditions2}).count()
            Que9Tijiao = QueCgx9.find({"$or":conditions2}).count()
            Que10Tijiao = QueCgx10.find({"$or":conditions2}).count()
            rows = []
            data = {
                'total': 1,
                'rows': rows
            }
            rows.append({
                'city': City,
                'region': Region,
                'towns': Towns,
                'Que7Tianxie': Que7Tianxie,
                'Que8Tianxie': Que8Tianxie,
                'Que9Tianxie': Que9Tianxie,
                'Que10Tianxie': Que10Tianxie,
                'Que7Tijiao': Que7Tijiao,
                'Que8Tijiao': Que8Tijiao,
                'Que9Tijiao': Que9Tijiao,
                'Que10Tijiao': Que10Tijiao,
            })
            return HttpResponse(json.dumps(data), content_type='application/json')
        data = {
            'total': 1,
            'rows':[
                {
                    'city': '待选择',
                    'region': '待选择',
                    'towns': '待选择',
                    'Que7Tianxie': '0',
                    'Que8Tianxie': '0',
                    'Que9Tianxie': '0',
                    'Que10Tianxie': '0',
                    'Que7Tijiao': '0',
                    'Que8Tijiao': '0',
                    'Que9Tijiao': '0',
                    'Que10Tijiao': '0',
                }
            ]
        }     
        return HttpResponse(json.dumps(data),content_type='application/json')      

#获取柱状图数据
def getCityNum(request):
    citys = ['株洲市','郴州市','常德市','张家界市','娄底市','益阳市','岳阳市','永州市']
    citysNum = []
    que7Num = []
    que8Num = []
    que9Num = []
    que10Num = []
    for city in citys:
        Num7 = QueCgx7.find({'所在的市':city,'是否需要再次编辑':{'$exists':1}}).count()
        Num8 = QueCgx8.find({'户籍地址所在的市':city,'是否需要再次编辑':{'$exists':1}}).count()
        Num9 = QueCgx9.find({'户籍地址所在的市':city,'是否需要再次编辑':{'$exists':1}}).count()
        Num10 = QueCgx10.find({'户籍地址所在的市':city,'是否需要再次编辑':{'$exists':1}}).count()
        que7Num.append({'name': city,'value': Num7})
        que8Num.append({'name': city,'value': Num8})
        que9Num.append({'name': city,'value': Num9})
        que10Num.append({'name': city,'value': Num10})
    citysNum.append(que7Num)
    citysNum.append(que8Num)
    citysNum.append(que9Num)
    citysNum.append(que10Num)
    return HttpResponse(json.dumps(citysNum))

#获取总统计数据
def getAllNum(request):
    if request.method == 'GET':
        Num7 = QueCgx7.find({'是否需要再次编辑':{'$exists':1}}).count()
        Num8 = QueCgx8.find({'是否需要再次编辑':{'$exists':1}}).count()
        Num9 = QueCgx9.find({'是否需要再次编辑':{'$exists':1}}).count()
        Num10 = QueCgx10.find({'是否需要再次编辑':{'$exists':1}}).count()
        rows = [
            {'que': '入户筛查表', 'num': Num7},
            {'que': '健康人群问卷', 'num': Num8},
            {'que': '脑出血患者问卷', 'num': Num9},
            {'que': '脑梗塞患者问卷', 'num': Num10}
        ]
        data = {
            'total': 1,
            'rows': rows
        }
    return HttpResponse(json.dumps(data), content_type='application/json') 

#获取调查员个人账号录入数量
@login_required
def searchQueNum(request):
    userinfo = UserInfo.objects.get(username=request.session['username'])
    #存储用户已填写数量
    quest7 = QueCgx7.find({"调查员签名": userinfo.name, '登录账号': userinfo.username, '是否需要再次编辑':{'$exists':1}}).count()  # 存储入户筛查表（湖南省)
    quest8 = QueCgx8.find({"调查员签字": userinfo.name, '登录账号': userinfo.username, '是否需要再次编辑':{'$exists':1}}).count()  # 存储健康人群问卷（湖南省）
    quest9 = QueCgx9.find({"调查员签字": userinfo.name, '登录账号': userinfo.username, '是否需要再次编辑':{'$exists':1}}).count()  # 脑出血患者调查问卷（湖南省）
    quest10 = QueCgx10.find({"调查员签字": userinfo.name, '登录账号': userinfo.username, '是否需要再次编辑':{'$exists':1}}).count()  # 脑梗塞患者调查问卷（湖南省）
    quest11 = QueCgx11.find({"调查员签字": userinfo.name, '登录账号': userinfo.username, '是否需要再次编辑':{'$exists':1}}).count()  # 街道乡镇级调查单位基本信息采集表（湖南省）
    #存储用户已提交数量
    Quest7 = QueCgx7.find({"调查员签名": userinfo.name, '登录账号': userinfo.username, "是否需要再次编辑":"否"}).count() 
    Quest8 = QueCgx8.find({"调查员签名": userinfo.name, '登录账号': userinfo.username, "是否需要再次编辑":"否"}).count() 
    Quest9 = QueCgx9.find({"调查员签名": userinfo.name, '登录账号': userinfo.username, "是否需要再次编辑":"否"}).count() 
    Quest10 = QueCgx10.find({"调查员签名": userinfo.name, '登录账号': userinfo.username, "是否需要再次编辑":"否"}).count() 
    Quest11 = QueCgx11.find({"调查员签名": userinfo.name, '登录账号': userinfo.username, "是否需要再次编辑":"否"}).count() 

    wenjuancount_tianxie = [quest7, quest8, quest9, quest10, quest11]  # 已填写问卷对应数目
    wenjuancount_tijiao = [Quest7, Quest8, Quest9, Quest10, Quest11]  # 已提交问卷对应数目
    print(wenjuancount_tianxie)
    print(wenjuancount_tijiao)
    return render(request, 'wenjuanresult/searchQueNum.html',
                  {'wenjuancount_tianxie': wenjuancount_tianxie, 'wenjuancount_tijiao': wenjuancount_tijiao, 'userinfo': userinfo})